package com.eims.sls_app.ui;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.AppTools;
import com.eims.sls_app.utils.MyAsynTaskWithProgress;
import com.eims.sls_app.utils.MyPushTask;
import com.eims.sls_app.view.MyToast;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.EmailHandler;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SmsHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import bls.juejin.cn.R;

/**
 * 设置
 * 
 * @author SLS003
 */
public class SettingActivity extends MyBaseActivity implements OnClickListener {
	private Context context = SettingActivity.this;
	private RelativeLayout rl_msg, rl_suggest, rl_share, setting_ll_update,
			setting_ll_resetpass, setting_ll_push, setting_ll_about;
	private ImageButton btn_random, btn_vibrator, btn_back;
	private Button setting_exit;
	private String opt = "16"; // 格式化后的 opt
	private String auth, info, time, imei, crc; // 格式化后的参数
	private TextView tv_count, settring_tv_updateNum;
	private MyAsynTask myAsynTask;
	private MyHandler myHandler;
	private SharedPreferences settings;
	private Editor editor;
	private long count = 0;
	private UMSocialService umSocialService;
	private static final String SHARE_PAGE = "com.umeng.share";
	private UMSocialService mController;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_appsetting);
		findView();
		initBtn();
		setListener();
	}

	private void findView() {
		myHandler = new MyHandler();
		rl_msg = (RelativeLayout) this.findViewById(R.id.setting_ll_message);
		rl_suggest = (RelativeLayout) this
				.findViewById(R.id.setting_ll_suggest);
		rl_share = (RelativeLayout) this.findViewById(R.id.setting_ll_share);
		setting_ll_update = (RelativeLayout) this
				.findViewById(R.id.setting_ll_update);
		setting_ll_resetpass = (RelativeLayout) this
				.findViewById(R.id.setting_ll_resetpass);
		setting_ll_push = (RelativeLayout) this
				.findViewById(R.id.setting_ll_push);
		setting_ll_about = (RelativeLayout) this
				.findViewById(R.id.setting_ll_about);
		btn_back = (ImageButton) findViewById(R.id.btn_back);
		tv_count = (TextView) this.findViewById(R.id.settring_tv_msgCount);
		settring_tv_updateNum = (TextView) this
				.findViewById(R.id.settring_tv_updateNum);
		btn_random = (ImageButton) this.findViewById(R.id.setting_btn_random);
		btn_vibrator = (ImageButton) this
				.findViewById(R.id.setting_btn_vibrator);
		setting_exit = (Button) findViewById(R.id.setting_exit);

		settings = getSharedPreferences("app_user", 0);
		editor = settings.edit();

	}

	private void initBtn() {
		if (settings.contains("isSensor")) {
			App.isSensor = settings.getBoolean("isSensor", true);
		}
		if (settings.contains("isVibrator")) {
			App.isVibrator = settings.getBoolean("isVibrator", true);
		}

		if (!App.isSensor)
			btn_random.setSelected(false);
		else
			btn_random.setSelected(true);

		if (!App.isVibrator)
			btn_vibrator.setSelected(false);
		else
			btn_vibrator.setSelected(true);
		settring_tv_updateNum.setText("当前版本" + App.version);
	}

	private void setListener() {
		rl_suggest.setOnClickListener(this);
		rl_msg.setOnClickListener(this);
		rl_share.setOnClickListener(this);
		setting_ll_update.setOnClickListener(this);
		setting_ll_resetpass.setOnClickListener(this);
		setting_ll_push.setOnClickListener(this);
		setting_ll_about.setOnClickListener(this);
		btn_back.setOnClickListener(this);
		btn_random.setOnClickListener(this);
		btn_vibrator.setOnClickListener(this);
		setting_exit.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.setting_ll_message:
			if (null == App.user) {
				Intent intent = new Intent(SettingActivity.this,
						LoginActivity.class);
				intent.putExtra("loginType", "msg");
				SettingActivity.this.startActivity(intent);
			} else {
				toMessage();
			}
			break;
		case R.id.setting_ll_update:// 检测版本更新
			MyAsynTask1 myAsynTask1 = new MyAsynTask1(context, "正在检测版本...");
			myAsynTask1.execute();
			break;
		case R.id.setting_ll_suggest:
			Intent intent = new Intent(SettingActivity.this,
					SuggestActivity.class);
			SettingActivity.this.startActivity(intent);
			break;
		case R.id.setting_ll_share:
			initUMShare();
			mController.openShare(this, false);
			break;
		case R.id.setting_ll_push:// 推送管理
			Intent intent_push = new Intent(context, PushManageActivity.class);
			context.startActivity(intent_push);
			break;
		case R.id.setting_ll_resetpass:// 修改密码
			Intent intent_repass = new Intent(context,
					UpdatePasswordActivity.class);
			context.startActivity(intent_repass);
			break;
		/** 全程关闭打开摇一摇 **/
		case R.id.setting_btn_random:
			App.isSensor = !App.isSensor;
			editor.putBoolean("isSensor", App.isSensor);
			editor.commit();
			setBtnText(btn_random, App.isSensor);
			break;
		/** 全程关闭打开震动 **/
		case R.id.setting_btn_vibrator:
			App.isVibrator = !App.isVibrator;
			editor.putBoolean("isVibrator", App.isVibrator);
			editor.commit();
			setBtnText(btn_vibrator, App.isVibrator);
			break;
		case R.id.setting_exit:
			exitLogin();
			break;
		case R.id.setting_ll_about:// 关于
			aboutApp();
			break;
		case R.id.btn_back:
			finish();
			break;
		}
	}

	private void aboutApp() {
		Intent intent = new Intent(context, AboutAppActivity.class);
		this.startActivity(intent);
	}

	private void setBtnText(ImageButton btn, boolean isOpen) {
		if (isOpen)
			btn.setSelected(true);
		else
			btn.setSelected(false);
	}

	private void toMessage() {
		Intent intent = new Intent(SettingActivity.this,
				AllMessageActivity.class);
		SettingActivity.this.startActivity(intent);
	}

	/**
	 * 异步任务 用来后台获取数据
	 */
	class MyAsynTask extends AsyncTask<Void, Integer, String> {
		/**
		 * 在后台执行的程序
		 */
		@Override
		protected String doInBackground(Void... params) {
			String error;
			// String key = MD5
			// .md5(App.user.getUserPass() == null ? "" :
			// App.user.getUserPass() + App.MD5_key);
			String key = App.key;
			info = RspBodyBaseBean.changeMsg_info(-1, 1, 10, 0);

			Log.i("x", "info-----" + info);
			crc = RspBodyBaseBean.getCrc(time, imei, key, info,
					App.user.getUid());
			auth = RspBodyBaseBean.getAuth(crc, time, imei,
					App.user.getUid());
			String value[] = { opt, auth, info };
			String result = HttpUtils.doPost(App.names, value,
					App.path);
			Log.i("x", "信息----------" + result);

			if ("-500".equals(result))
				return "-500";
			try {
				JSONObject object = new JSONObject(result);
				String smsList = object.getString("stationSMSList");

				JSONArray array = new JSONArray(smsList);
				if (array.length() == 0)
					return "-2";
				error = object.getString("error");
				Log.i("x", "array-------" + array);
				for (int i = 0; i < array.length(); i++) {
					JSONObject item = array.getJSONObject(i);
					count = item.getLong("RecordCount");
					return "0";
				}
			} catch (Exception e) {
				Log.i("x", "拿站内信错误" + e.getMessage());
				error = "-2";
			}
			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			myHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	class MyAsynTask1 extends MyAsynTaskWithProgress {
		/**
		 * @param context
		 *            上下文
		 * @param title
		 *            进度框显示文字
		 */
		public MyAsynTask1(Context context, String title) {
			super(context, title);
		}

		@Override
		protected String doInBackground(Integer... params) {
			String key = MD5.md5(App.MD5_key);
			time = RspBodyBaseBean.getTime();
			info = "{\"identify\":\"android\",\"appversion\":\""
					+ AppTools.getVerName(getApplicationContext()) + "\"}";
			imei = RspBodyBaseBean.getIMEI(context);
			crc = RspBodyBaseBean.getCrc(time, imei, key, info, "-1");
			auth = RspBodyBaseBean.getAuth(crc, time, imei, "-1");
			opt = "0";
			String[] values = { opt, auth, info };
			String result = HttpUtils.doPost(App.names, values,
					App.path);
			Log.i("x", "版本更新--->info" + info);
			Log.i("x", "版本更新--->result" + result);
			try {
				JSONObject jsonObject = new JSONObject(result);
				App.appobject.setUpgrade(jsonObject.optString("upgrade"));
				// App.appobject.setApkName(jsonObject.optString("apkName"));
				App.appobject.setVersionCode(jsonObject
						.optString("currentappversion"));
				App.appobject.setDownLoadUrl(jsonObject
						.optString("downLoadUrl"));
				if (App.appobject.getUpgrade().equals("True")) {
					return "SU";
				} else
					return "False";
			} catch (JSONException e) {
				return "-500";
			}
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result.equals("SU")) {
				myHandler.sendEmptyMessage(1);
			} else
				myHandler.sendEmptyMessage(-1);
		}
	}

	/**
	 * 处理页面显示的
	 */
	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case App.ERROR_SUCCESS:
				if (0 == count)
					return;
				tv_count.setText("您有" + count + "条未读消息");
				break;
			case 1:// 更新
					// 这里来检测版本是否需要更新
				UpdateManager mUpdateManager = new UpdateManager(context,
						App.appobject.getDownLoadUrl());
				mUpdateManager.checkUpdateInfo();
				break;
			case -1:// 当前是最新版本
				MyToast.getToast(context, "当前版本为最新版本").show();
				break;
			case -2:// 没有消息
				tv_count.setText("");
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}

	@Override
	protected void onResume() {
		tv_count.setText("");
		if (null == App.user) {
			tv_count.setText("您还没登录");
		} else {
			myAsynTask = new MyAsynTask();
			myAsynTask.execute();
		}
		super.onResume();
	}

	/**
	 * 退出登陆
	 */
	private void exitLogin() {
		App.user = null;
		Intent intent = new Intent(context, LoginActivity.class);
		context.startActivity(intent);
		settings = context.getSharedPreferences("app_user", 0);
		Editor editor = settings.edit();
		editor.putBoolean("isLogin", false);
		editor.putString("uid", "-1");
		editor.commit();
		App.Status = "0";
		MyPushTask.newInstances(context).commit();
		finish();
	}

	private void initUMShare() {
		if (mController == null) {
			String url = App.Qpath;
			mController = UMServiceFactory.getUMSocialService(SHARE_PAGE);
			QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this,
					"100424468", "c7394704798a158208a74ab60104f0ba");
			qZoneSsoHandler.setTargetUrl(url);
			qZoneSsoHandler.addToSocialSDK();
			SmsHandler sms = new SmsHandler();
			sms.addToSocialSDK();
			EmailHandler email = new EmailHandler();
			email.addToSocialSDK();
			// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
			// TODO 根据需求进行修改，签名生成文件 key.keystore
			String appID = "wxee5afb24aed1c6ff";
			String appSecret = "6fd3d5581313c9b657dad9cf3d42b48a";
			// 添加微信平台
			UMWXHandler wxHandler = new UMWXHandler(this, appID, appSecret);
			wxHandler.setTargetUrl(url);
			wxHandler.addToSocialSDK();
			// 支持微信朋友圈
			UMWXHandler wxCircleHandler = new UMWXHandler(this, appID,
					appSecret);
			wxCircleHandler.setTargetUrl(url);
			wxCircleHandler.setToCircle(true);
			wxCircleHandler.addToSocialSDK();
			// 设置显示的平台和顺序
			mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN,
					SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QZONE,
					SHARE_MEDIA.SINA, SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN,
					SHARE_MEDIA.SMS, SHARE_MEDIA.EMAIL);
			// 设置平台顺序
			mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN,
					SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QZONE,
					SHARE_MEDIA.SINA, SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN,
					SHARE_MEDIA.SMS, SHARE_MEDIA.EMAIL);
			mController.setShareContent("联盈助手系统" + url);
			// 人人网
			mController.setAppWebSite(SHARE_MEDIA.RENREN, url);
			mController
					.setShareMedia(new UMImage(this, R.drawable.icon_new));
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}
}
